/**
 *   
 * This code is originally written by Android-er 
 * http://android-er.blogspot.com/2010/01/implement-simple-file-explorer-in.html
 * and modified by me.
 * 
 * @author prebz
 *
 */

package com.wirelesstransfer.activity.filebrowser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.wirelesstransfer.R;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class FileBrowser extends ListActivity implements OnClickListener{

	// Variables for adding text to the listView
	private List<String> item = null;			
	private List<String> itemSize = null;
	public List<String> path = null;
	
	private String root="/";	
		
	private Map<String, String> fileSize;
	
	public final static String FILESIZE = "fileSize";
	public final static String UNIT = "unit";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filebrowser);
				
		getDir(root);			
	}

	// Will be used in other classes
	public void onClick(View v) {}

	/**
	 * Gets the files/maps and adds to List as a string
	 * where you can retrieve information about the structure
	 * in the file system
	 * @param dirPath
	 */
	public void getDir(String dirPath)
	{

		item = new ArrayList<String>();
		itemSize = new ArrayList<String>();
		path = new ArrayList<String>();

		File f = new File(dirPath);
		File[] files = f.listFiles();

		if(!dirPath.equals(root)){
			item.add(root);
			path.add(root);
			itemSize.add("");

			item.add("../");
			path.add(f.getParent());
			itemSize.add("");
		}

		// Loop for adding all the files/maps in item.
		for(int i=0; i < files.length; i++)
		{
			File file = files[i];
			path.add(file.getPath());

			if(file.isDirectory()){
				item.add(file.getName() + "/");
				itemSize.add("");
			}
			else{
				item.add(file.getName());
				
				fileSize = FileSize.getFileSize(file);
				itemSize.add(fileSize.get(FILESIZE) + " " + fileSize.get(UNIT));
			}
		}

		setListAdapter(new CustomArrayAdapter(this, item, itemSize));

	}
	
	/**
	 * add all fileNames to listView
	 * @param allFiles the files to display
	 */
	public void listAllFiles(List<File> allFiles){
		
		item = new ArrayList<String>();
		itemSize = new ArrayList<String>();
		path = new ArrayList<String>();
		
		// Loop for adding all the files/maps
		for(File file: allFiles){
			fileSize = FileSize.getFileSize(file);
			path.add(file.getPath());
			item.add(file.getName());
			itemSize.add(fileSize.get(FILESIZE) + " " + fileSize.get(UNIT));
		}
		
		setListAdapter(new CustomArrayAdapter(this, item,itemSize));

	}
	
		/**
	 * create a toast
	 * @param text to be displayed
	 */
	public void displayToast(String text) {
		Toast.makeText(getApplicationContext(), text
				,  Toast.LENGTH_SHORT).show();	
	}

}
